package com.cmw.auntapp.core.util;

import android.util.Log;

import androidx.annotation.Nullable;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Source;

/**
 * @desc: 自定义类实现okhttp3 监听上传文件进度
 * @author: chengmingwei
 * @date: 2021/5/11 9:24 PM
 * @contact: phone(微信同号):13922111489 / email: 340360491@qq.com
 */
public class ProgressRequestBody extends RequestBody {
    public static final String TAG = "ProgressRequestBody";

    public interface ProgressListener {
        void transferred( long cur,long total );
    }

    private RequestBody mRequestBody;
    private int mCurrentLength;
    private ProgressListener progressListener;

    public ProgressRequestBody(MultipartBody requestBody) {
        this.mRequestBody = requestBody;
    }

    public ProgressRequestBody(MultipartBody requestBody, ProgressListener progressListener) {
        this.mRequestBody = requestBody;
        this.progressListener = progressListener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        // 静态代理最终还是调用的代理对象的方法
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Log.e(TAG,"监听");
        // 总的长度
        final long contentLength = contentLength();
        // 获取当前写了多少数据？BufferedSink Sink(okio 就是 io )就是一个 服务器的 输出流，我还是不知道写了多少数据

        // 又来一个代理 ForwardingSink
        ForwardingSink forwardingSink = new ForwardingSink(sink) {
            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                // 每次写都会来这里
                mCurrentLength += byteCount;
                if(progressListener!=null){
                    long currLengthKb = 0L;
                    long conentLengthKb = contentLength / 1024; // 转成KB
                    if (mCurrentLength < contentLength) {
                        currLengthKb = mCurrentLength / 1024;
                    } else {
                        currLengthKb = conentLengthKb;
                    }
                    progressListener.transferred(currLengthKb, conentLengthKb);
                }
                Log.e(TAG,contentLength+" : "+mCurrentLength);
                super.write(source, byteCount);
            }
        };
        // 转一把
        BufferedSink bufferedSink = Okio.buffer(forwardingSink);
        mRequestBody.writeTo(bufferedSink);
        // 刷新，RealConnection 连接池
        bufferedSink.flush();
        bufferedSink.close();
    }

}

